package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.FontSubstitutionSettings;
import com.aspose.words.LoadOptions;
import com.aspose.words.NodeCollection;
import com.aspose.words.NodeType;
import com.aspose.words.Table;

/**
 * @Description TODO(这里用一句话描述这个类的作用)
 *
 * @author liuqinghua
 * @date 2024-7-26
 */
public class AsposeWordToPdf {

    public static void wordToPdf(File inputFile, OutputStream outputStream, boolean delInputFile) {
        InputStream inputStream = null;
        try {
            String os = System.getProperty("os.name");
            LoadOptions loadOptions = new LoadOptions();
            if (os != null && os.contains("nix") || os.contains("nux") || os.contains("mac")) {
                // apose在linux服务器上生成pdf，内容乱码问题，解决代码：将windows的字体上传到linux，取linux上的字体列表
                FontSettings fontSettings = FontSettings.getDefaultInstance();
                fontSettings.setFontsFolder(
                        File.separator + "usr" + File.separator + "share" + File.separator + "fonts" + File.separator,
                        true);
                FontSubstitutionSettings substitutionSettings = fontSettings.getSubstitutionSettings();
                substitutionSettings.getTableSubstitution().addSubstitutes("Arial", "DejaVu Sans");
//                LoadOptions loadOptions = new LoadOptions();
                loadOptions.setFontSettings(fontSettings);
            }
            inputStream = new FileInputStream(inputFile);
            Document doc = new Document(inputStream, loadOptions);
//            doc.setJustificationMode(JustificationMode.EXPAND);
            NodeCollection childNodes = doc.getChildNodes(NodeType.TABLE, true);
            for (int i = 0; i < childNodes.getCount(); i++) {
                // 获取文档中的第一个表格
                Table table = (Table) doc.getChild(NodeType.TABLE, i, true);
                // 设置表格不自动适应宽度
                table.setAllowAutoFit(false);
            }
            doc.save(outputStream, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {

                inputStream.close();
                outputStream.close();
                if (delInputFile && inputFile.exists()) {
                    inputFile.delete();
                }
            } catch (Exception e) {

            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        FileOutputStream outputStream = new FileOutputStream(new File("d:/a234.pdf"));
        wordToPdf(new File("d:/a234.docx"), outputStream, true);
    }
}
